#region using

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core;

#endregion

/// <summary>
/// Displays a list of child pages for the current page where [childpages] is found in the page body.
/// </summary>
[Extension("Displays a list of child pages for the current page where [childpages] is found in the page body", "1.2", "BlogEngine.NET")]
public class ChildPages
{
    /// <summary>
    /// Hooks up an event handler to the Post.Serving event.
    /// </summary>
    public ChildPages()
    {
        BlogEngine.Core.Page.Serving += new EventHandler<ServingEventArgs>(Page_Serving);
    }

    /// <summary>
    /// Handles the Page.Serving event to take care of the [childpages] keyword.
    /// </summary>
    private void Page_Serving(object sender, ServingEventArgs e)
    {
        if (!e.Body.Contains("[childpages]"))
        {
            return;
        }

        string newString = string.Empty;

        if (SiteMap.CurrentNode != null && SiteMap.CurrentNode.HasChildNodes)
        {
            HtmlGenericControl ul = BuildSubPageList();

            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                ul.RenderControl(new HtmlTextWriter(sw));
                newString = sw.ToString();
            }
        }

        e.Body = e.Body.Replace("[childpages]", newString);
    }

    /// <summary>
    /// Loops through all child pages and builds html UL list collection.
    /// </summary>
    private static HtmlGenericControl BuildSubPageList()
    {
        HtmlGenericControl ul = new HtmlGenericControl("ul");

        foreach (SiteMapNode node in SiteMap.CurrentNode.ChildNodes)
        {
            HtmlGenericControl li = new HtmlGenericControl("li");
            HtmlAnchor anchor = new HtmlAnchor();

            anchor.HRef = node.Url;
            anchor.InnerHtml = node.Title;
            anchor.Title = node.Description;

            li.Controls.Add(anchor);
            ul.Controls.Add(li);
        }

        return ul;
    }
}
